package nl.ru.rd.facedetection.nnbfd;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;

/**
 * A preprocessor used in the NNBFD for images.
 * 
 * Converts the image to grayscale, stores it in a matrix, and uses histogram and linear equalization.
 * 
 * @author Wouter Geraedts (s0814857 - wgeraedts) PGP 66AA5935
 */
public class Preprocessor
{
	/**
	 * Converts the image to grayscale and stores it in a matrix.
	 * 
	 * @param colorImage
	 *            The image to be converted.
	 * @return A matrix with the applied conversion.
	 */
	public static Matrix toMatrix(BufferedImage colorImage)
	{
		int height = colorImage.getHeight();
		int width = colorImage.getWidth();

		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
		Graphics g = image.getGraphics();
		g.drawImage(colorImage, 0, 0, null);
		g.dispose();

		Raster raster = image.getData();

		Matrix matrix = new Matrix(width, height);
		for(int y = 0; y < height; y++)
			for(int x = 0; x < width; x++)
				matrix.setValue(x, y, (short) raster.getSample(x, y, 0));

		return matrix;
	}

	/**
	 * Equalize a matrix using histogram and linear equalization.
	 * 
	 * @param matrix
	 *            The matrix to be equalized.
	 */
	public static void equalize(Matrix matrix)
	{
		HistogramEqualizer histogramEq = new HistogramEqualizer();
		LinearEqualizer linearEq = new LinearEqualizer();

		linearEq.equalize(matrix);
		histogramEq.equalize(matrix);
	}
}
